package com.alpesressources.comexpert;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.alpesressources.comexpert.bo.IObject;
import com.alpesressources.comexpert.bo.Schema;
import com.alpesressources.comexpert.bo.request.GetSchemaRequest;
import com.alpesressources.comexpert.bo.response.ErrorResponse;
import com.alpesressources.comexpert.bo.response.Response;
import com.alpesressources.comexpert.bo.response.ErrorResponse.EnumErrorCode;
import com.alpesressources.comexpert.bo.response.GetSchemaResponse;
import com.alpesressources.comexpert.bo.response.ResponseObject.EnumResult;
import com.alpesressources.comexpert.dao.DaoManager;
import com.alpesressources.comexpert.exception.DaoException;
import com.alpesressources.comexpert.util.MyJsonSerializer;
import java.util.Map;

public class GetSchema extends AAction {

	private static Logger logger = Logger.getLogger(GetSchema.class);
	
	@Override
	public void processGet(ServletConfig config,
			HashMap<String, Object> queryString, HttpServletResponse response)
			throws ServletException, IOException {
	}

	@Override
	public void processPost(ServletConfig config,
			HashMap<String, Object> queryString, IObject postRequest,
			HttpServletResponse response) throws ServletException, IOException {
		GetSchemaRequest getSchemaRequest = (GetSchemaRequest) postRequest;

		GetSchemaResponse getSchemaResponse = new GetSchemaResponse();
		
		if (getSchemaRequest.getTableName() != null) {
			
			try {
				DaoManager daoManager=new DaoManager(queryString.get("dossier").toString());
				
				Map<String, Schema> schemas = daoManager.getSchema(getSchemaRequest.getTableName());
				
				getSchemaResponse.setResult(EnumResult.OK);
				getSchemaResponse.setSchemas(schemas);
				
			} catch (DaoException e) {
				getSchemaResponse.setResult(EnumResult.NOK);
				
				logger.error(e);
			}
		} else {
			getSchemaResponse.setResult(EnumResult.NOK);

			logger.info("getSchema failed: all required fields are not present in the request");
		}

		logger.info(getSchemaResponse);

		Response r = new Response();
		ErrorResponse errorResponse = new ErrorResponse();

		errorResponse.setErrorCode(EnumErrorCode.NO_ERROR);
		r.setErrorResponse(errorResponse);

		r.getData().add(getSchemaResponse);

		MyJsonSerializer myJsonSerializer = new MyJsonSerializer();

		response.getOutputStream().write(
				myJsonSerializer.serialize(r).getBytes());
	}

	@Override
	public Class<?> getObjectClass() {
		return GetSchemaRequest.class;
	}

}
